package day_7_5;

import java.util.LinkedList;
import java.util.Queue;

public class Main2 {
    /**
     * 111. 二叉树的最小深度
     * https://leetcode.cn/problems/minimum-depth-of-binary-tree/description/
     */
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    public int minDepth(TreeNode root) {
        // 广度
        if(root == null) {
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int depth = 0;
        while(!queue.isEmpty()) {
            int size = queue.size();
            depth++;
            TreeNode cur = null;
            for(int i = 0;i < size;i++) {
                cur = queue.poll();

                if(cur.left == null && cur.right == null) {
                    return depth;
                }

                if(cur.left != null) {
                    queue.offer(cur.left);
                }
                if(cur.right != null) {
                    queue.offer(cur.right);
                }
            }
        }
        return depth;
    }
    public int minDepth1(TreeNode root) {
        // 深度
        if(root == null) {
            return 0;
        }

        if(root.left == null) {
            return minDepth1(root.right) + 1;
        }

        if(root.right == null) {
            return minDepth1(root.left) + 1;
        }

        return Math.min(minDepth1(root.left),minDepth1(root.right)) + 1;
    }
}
